<?php

//查询
function select($config, $table, $where = '')
{
    //执行公共部分
    common($config);
    // 5. 准备SQL语句
    $sql = "select * from `{$table}` {$where}";
    // 6. 发送SQL语句到MySQL服务器
    $res = mysql_query($sql);
    // 7. 处理结果集
    while ($row = mysql_fetch_assoc($res)) {
        $result[] = $row;
    }
    // 8.释放结果集资源，关闭数据库连接
    mysql_free_result($res); //如果是dml语句 这一句不需要
    mysql_close();

    return $result;
}

//删除
function del($config, $table, $id)
{
    common($config);
    $sql = "delete from `{$table}` where id={$id}";
    mysql_query($sql);
    $rows = mysql_affected_rows();
    mysql_close();

    return $rows;
}

//添加
function add($config, $table, $aa)
{
    common($config);

    $field = '`' . implode('`,`', array_keys($aa)) . '`';
    $value = "'" . implode("','", $aa) . "'";

    $sql  = "insert into `{$table}`({$field}) values({$value})";
    $res  = mysql_query($sql);
    $rows = mysql_affected_rows();
    mysql_close();

    return $rows;
}

//修改
function update($config, $table, $bb)
{
    common($config);

    $change = '';
    foreach ($bb as $k => $v) {
        $change .= "`{$k}`='{$v}',";
    }

    $change = rtrim($change, ',');

    $sql = "update `{$table}` set {$change} where id={$bb['id']}";

    mysql_query($sql);
    $rows = mysql_affected_rows();
    mysql_close();
    return $rows;
}

//公共部分
function common($config)
{
    // 1. 连接MySQL数据库服务器 mysql -h localhost -u root -p root
    @mysql_connect($config['host'], $config['user'], $config['pwd']);
    // 2. 判断是否连接正确
    if (mysql_errno()) {
        die('连接失败,错误原因：' . mysql_error());
    }
    // 3. 选择数据库
    mysql_select_db($config['db']);
    // 4. 设置字符集
    mysql_set_charset($config['char']);
}
